"""
构建图网络模型训练  ： 直推式学习
"""
import pandas as pd
import torch
import torch.nn.functional as F
from torch_geometric.datasets import Planetoid
from torch_geometric.loader import NeighborLoader
from torch_geometric.nn import SAGEConv, GCNConv, GATConv, TransformerConv
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
import yaml
from utils import read_yaml, construct_graph_data, show_train_valid_loss_curve, visualize, get_file_name, get_diy_data, \
    get_cora_data, set_seed

set_seed(0)

# 设备设置
config = read_yaml("./config.yaml")
device = config["model_config"]["device"]
num_features = config["data_config"]["num_features"]
num_classes = config["data_config"]["num_classes"]
model_name = config["model_config"]["graph_model_name"]
dataset_name = config["data_config"]["experiment_dataset_name"]
print(f"Using device: {device}")

if dataset_name == "cora":
    data = get_cora_data()
    num_features = config["data_config"]["cora"]["num_features"]
    num_classes = config["data_config"]["cora"]["num_classes"]
else:
    data = get_diy_data()


# 定义GraphModel模型
class GraphModel(torch.nn.Module):
    def __init__(self, in_channels, hidden_channels, out_channels):
        super().__init__()
        self.conv1 = eval(model_name)(in_channels, hidden_channels)
        self.conv2 = eval(model_name)(hidden_channels, out_channels)

    def forward(self, x, edge_index):
        x = self.conv1(x, edge_index)
        x = F.relu(x)
        x = F.dropout(x, p=0.5, training=self.training)
        x = self.conv2(x, edge_index)
        return x


# 初始化模型
model = GraphModel(
    in_channels=num_features,
    hidden_channels=128,
    out_channels=num_classes
).to(device)

optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)
criterion = torch.nn.CrossEntropyLoss()

print(model)


# 训练函数
def train():
    model.train()
    total_loss = 0
    optimizer.zero_grad()
    out = model(data.x, data.edge_index)
    loss = criterion(out[data.train_mask], data.y[data.train_mask])
    loss.backward()
    optimizer.step()
    total_loss += loss.item()
    return total_loss


# 测试函数
@torch.no_grad()
def test(mask):
    model.eval()
    # 使用全图进行测试（实际应用中可按需采样）
    out = model(data.x, data.edge_index)
    pred = out.argmax(dim=1)
    acc = (pred[mask] == data.y[mask]).sum() / mask.sum()
    return acc.item(), out


# 训练循环
train_losses = []
val_accs = []
test_accs = []

for epoch in range(1, 101):
    loss = train()
    train_losses.append(loss)
    val_acc, _ = test(data.valid_mask)
    test_acc, _ = test(data.test_mask)
    val_accs.append(val_acc)
    test_accs.append(test_acc)
    if epoch % 10 == 0:
        print(f'Epoch {epoch:03d}, Loss: {loss:.4f}, Val: {val_acc:.4f}, Test: {test_acc:.4f}')

# 绘图展示 loss 和 accuracy
show_train_valid_loss_curve(train_losses=train_losses, val_accs=val_accs, test_accs=test_accs, prefix=get_file_name())

# 最终测试
final_val_acc, val_out = test(data.valid_mask)
final_test_acc, test_out = test(data.test_mask)
print(f'Final Validation Accuracy: {final_val_acc:.4f}')
print(f'Final Test Accuracy: {final_test_acc:.4f}')

visualize(model=model, out=test_out, mask=data.test_mask, y=data.y, prefix=get_file_name())
